<template>
  <div class="padding-lr-xs approved-by">
    <a-form
      v-if="!~['bpmn:CallActivity', 'bpmn:SubProcess'].indexOf(formData.type)"
    >
      <a-divider><span class="text-bold">节点审批人员</span></a-divider>
      <a-form-item
        class="label-width"
        v-if="formData.type == 'bpmn:UserTask'"
        label=""
      >
        <a-divider
          ><span style="color: green;">可参与会签人员类型</span></a-divider
        >
        <a-radio-group
          size="small"
          v-model="formData.userType"
          @change="changeUserType"
        >
          <a-radio value="candidateUsers">
            指定成员
          </a-radio>
          <a-radio value="candidateGroups">
            指定岗位角色
            <a-tooltip placement="bottomRight" overlayClassName="custom-tip">
              <template slot="title">
                <div style="display: flex;">
                  <div>
                    <h3>什么是岗位角色？</h3>
                    <p style="margin-bottom: 8px;">
                      岗位角色指团队成员的专业分工类别，如人事、行政、财务等，每类岗位角色可由
                      1 位或多位成员组成。
                    </p>
                    <h3>如何使用岗位角色？</h3>
                    <p>
                      用岗位角色作为审批人，当有成员离职变动时，该岗位角色中的其他成员可继续完成审批，从而避免审批流程失效的情况。
                    </p>
                    <p>
                      提示：若选择的岗位角色中包含多名成员，则岗位角色中所有成员成为审批人。
                    </p>
                  </div>
                </div>
              </template>
              <a-icon type="question-circle" />
            </a-tooltip>
          </a-radio>
          <!-- <a-radio value="department">
            指定岗位
          </a-radio> -->
          <a-divider
            ><span style="color: red;">不可参与会签人员类型</span></a-divider
          >
          <a-radio value="processInitiator">
            流程发起人
            <a-tooltip placement="bottomRight">
              <template slot="title">
                将发起人本人设置为审批人，可用于需要发起人进行信息复核的场景
              </template>
              <a-icon type="question-circle" />
            </a-tooltip>
          </a-radio>
          <a-radio value="departmentHead">
            部门主管
          </a-radio>
          <a-radio value="reportsTo">
            直属主管
          </a-radio>
          <a-radio value="memberFields">
            表单变量
          </a-radio>
        </a-radio-group>
      </a-form-item>
      <!-- 添加成员 -->
      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        v-if="
          formData.type == 'bpmn:UserTask' && formData.userType === 'assignee'
        "
      >
        <a-button type="primary" @click="() => (isUserPopups = true)">
          <a-icon @click="() => (isUserPopups = true)" type="plus" />
          添加成员
        </a-button>
        不能超过25人
        <a-input
          key="1"
          v-model="formData.assigneeName"
          placeholder="请选择"
          @change="
            (e) =>
              setUser({
                assignee: formData.assigneeName,
                assigneeName: formData.assigneeName,
              })
          "
        >
          <a-icon
            slot="addonAfter"
            type="user"
            @click="() => (isUserPopup = true)"
          />
        </a-input>
        <user-popup
          :visible="isUserPopup"
          style="width: 100%;"
          :typeForm="true"
          :typeNum="1"
          @change="(value) => addUser(value, 'assignee')"
          @close="() => (isUserPopup = false)"
        />
      </a-form-item>
      <!-- 选择审批人 -->
      <a-form-item
        v-else-if="
          formData.type == 'bpmn:UserTask' &&
            formData.userType === 'candidateUsers'
        "
      >
        <span class="title">选择审批人</span>
        <personnel-popup
          placeholder="请选择人员"
          v-model="formData.candidateUsersName"
          :multiple="true"
          url="/mdata/organization/getTreeProAndUserData"
          @change="
            (value, data) => {
              setUser({
                candidateUsers: formData.candidateUsersName,
                candidateUsersName: formData.candidateUsersName,
              }),
                addUser(
                  {
                    userName: data.map((e) => e.userNameId).toString(),
                    userNameId: data.map((e) => e.userNameId).toString(),
                  },
                  'candidateUsers'
                );
            }
          "
        ></personnel-popup>
        <a-alert
          message="注意当指定成员选择了多个成员而没有设置会签时 一个人同意后该流程即通过"
          banner
        />
      </a-form-item>
      <!-- 指定岗位角色 -->
      <a-form-item
        v-else-if="
          formData.type == 'bpmn:UserTask' &&
            formData.userType === 'candidateGroups'
        "
      >
        <span class="title">选择岗位角色</span>
        <a-input
          key="2"
          readOnly
          v-model="formData.candidateGroupsName"
          placeholder="请选择岗位角色"
          @click="() => (isUserPopups = true)"
          @change="
            (e) =>
              setUser({
                candidateGroups: formData.candidateGroupsName,
                candidateGroupsName: formData.candidateGroupsName,
              })
          "
        >
        </a-input>
        <role-popup
          :userList="formData.candidateGroups"
          :visible="isUserPopups"
          style="width: 100%;"
          :typeNum="2"
          @change="(value) => addUser(value, 'candidateGroups')"
          @close="() => (isUserPopups = false)"
        />
        <a-alert
          message="注意当指定岗位角色选择了多个岗位角色而没有设置会签时 一个人同意后该流程即通过"
          banner
        />
      </a-form-item>
      <!-- 流程发起人 -->
      <a-form-item
        v-else-if="
          formData.type == 'bpmn:UserTask' &&
            formData.userType === 'processInitiator'
        "
      >
        <a-alert message="发起人自己将作为审批人处理审批" banner />
        <a-input
          v-model="formData.processInitiator"
          type="hidden"
          :default-value="'${startUserNameId}'"
          disabled
        ></a-input>
      </a-form-item>
      <!-- 岗位 -->
      <a-form-item
        v-else-if="
          formData.type == 'bpmn:UserTask' && formData.userType === 'department'
        "
      >
        <span class="title">选择岗位</span>
        <a-input
          key="3"
          readOnly
          v-model="formData.candidateGroupsName"
          placeholder="请选择岗位"
          @click="() => (isUserPopups = true)"
          @change="
            (e) =>
              setUser({
                candidateGroups: formData.candidateGroupsName,
                candidateGroupsName: formData.candidateGroupsName,
              })
          "
        >
        </a-input>
        <t-department
          :userList="formData.candidateGroups"
          :visible="isUserPopups"
          style="width: 100%;"
          :typeNum="2"
          @change="(value) => addUser(value, 'department')"
          @close="() => (isUserPopups = false)"
        />
        <a-alert
          message="注意当指定岗位选择了多个岗位而没有设置会签时 一个人同意后该流程即通过"
          banner
        />
      </a-form-item>
      <!-- 部门主管 -->
      <template
        v-else-if="
          formData.type == 'bpmn:UserTask' &&
            formData.userType === 'departmentHead'
        "
      >
        <a-form-item>
          <a-alert message="发起人的部门主管将作为审批节点" banner />
        </a-form-item>
      </template>
      <template
        v-else-if="
          formData.type == 'bpmn:UserTask' &&
            formData.userType === 'continuousMultiLevelSupervisor'
        "
      >
        <a-form-item label="审批终点">
          <a-radio-group
            v-model="approvalEndPointValue"
            @change="approvalEndPointChange"
          >
            <a-radio :style="radioStyle" :value="1">
              指定岗位角色（同时是主管线上的主管）
              <a-input
                :disabled="approvalEndPointValue !== 1"
                style="width: 160px;"
                @click.stop="() => (isUserPopups = true)"
                key="2"
                v-model="formData.candidateUsersName"
                placeholder="请选择"
                @change="
                  (e) =>
                    setUser({
                      candidateUsers: formData.candidateUsersName,
                      candidateUsersName: formData.candidateUsersName,
                    })
                "
              >
                <a-icon
                  slot="addonAfter"
                  type="user"
                  @click.stop="() => (isUserPopups = true)"
                />
              </a-input>
              <user-popup
                :visible="isUserPopups"
                style="width: 100%;"
                :typeForm="true"
                :typeNum="1"
                @change="
                  (value) => addUser(value, 'continuousMultiLevelSupervisor')
                "
                @close="() => (isUserPopups = false)"
              />
            </a-radio>
            <a-checkbox
              v-model="approvalEndPointSecondLevelValue"
              :disabled="approvalEndPointValue !== 1"
              style="margin-left: 30px;"
            >
              同时不超过发起人向上的
              <a-select
                :disabled="!approvalEndPointSecondLevelValue"
                default-value="1"
                style="width: 160px"
              >
                <a-select-option value="1">
                  一级主管
                </a-select-option>
                <a-select-option value="2">
                  二级主管
                </a-select-option>
              </a-select>
            </a-checkbox>
            <a-radio :style="radioStyle" :value="2">
              通讯录中的
              <a-select
                :disabled="approvalEndPointValue !== 2"
                default-value="1"
                style="width: 160px"
              >
                <a-select-option value="1">
                  最高级主管
                </a-select-option>
                <a-select-option value="2">
                  一级主管
                </a-select-option>
                <a-select-option value="3">
                  二级主管
                </a-select-option>
              </a-select>
            </a-radio>
          </a-radio-group>
        </a-form-item>
      </template>
      <template
        v-else-if="
          formData.type == 'bpmn:UserTask' && formData.userType === 'reportsTo'
        "
      >
        <a-form-item>
          <span class="title">选择直属主管</span>
          <div>
            <a-select default-value="1" style="width: 120px">
              <a-select-option value="1">
                发起人
              </a-select-option>
            </a-select>
            的
            <a-select default-value="1" style="width: 120px">
              <a-select-option value="1">
                一级主管
              </a-select-option>
            </a-select>
          </div>
        </a-form-item>
      </template>
      <template
        v-else-if="
          formData.type == 'bpmn:UserTask' &&
            formData.userType === 'departmentContactPerson'
        "
      >
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="选择部门接口人"
        >
          <a-select default-value="1" style="width: 120px">
            <a-select-option value="1">
              发起人
            </a-select-option>
          </a-select>
          的
          <a-select default-value="1" style="width: 120px">
            <a-select-option value="1">
              一级主管
            </a-select-option>
            <a-select-option value="2">
              二级主管
            </a-select-option>
          </a-select>
        </a-form-item>
      </template>
      <template
        v-else-if="
          formData.type == 'bpmn:UserTask' &&
            formData.userType === 'selectedByTheInitiator'
        "
      >
        <a-form-item label="发起人自选">
          <a-radio-group :default-value="1">
            <a-radio :value="1">
              全公司
            </a-radio>
            <a-radio :value="2">
              指定成员
            </a-radio>
            <a-radio :value="3">
              指定岗位角色
            </a-radio>
          </a-radio-group>
        </a-form-item>
      </template>
      <template
        v-else-if="
          formData.type == 'bpmn:UserTask' &&
            formData.userType === 'thirdPartyServices'
        "
      >
        <span class="title">第三方接口服务审批人</span>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="">
          <a-input style="width: 100%" placeholder="接口服务"> </a-input>
        </a-form-item>
      </template>
      <a-form-item
        v-else-if="
          formData.type == 'bpmn:UserTask' &&
            formData.userType === 'memberFields'
        "
      >
        <span class="title">选择表单内的字段作为审批人</span>
        <a-select
          show-search
          style="width: 100%"
          placeholder="请选择表单成员字段"
          v-model="formData.candidateUsersName"
          option-filter-prop="children"
          :filter-option="filterOption"
          @change="
            (value, option) =>
              addUser({ filed: value, filedList: option }, 'memberFields')
          "
        >
          <a-select-option
            v-for="item in memberFieldList"
            :key="item.filed"
            :value="item.filed"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
        <a-alert message="注意：当表单选择系统表单时表单变量会失效" banner />
      </a-form-item>
      <a-alert
        message="会签状态下重新选择审批人会清空会签状态，请选择完审批人员后再次设置会签类型"
        banner
      />
    </a-form>
  </div>
</template>

<script>
import userPopup from "@/components/TopVUI/custom/userPopup";
import rolePopup from "@/components/TopVUI/custom/rolePopup";
import TDepartment from "./components/TDepartment";
import buttonPopup from "./modal/buttonModal.vue";
import multiInstance from "./modal/multiInstance.vue";
import tableForm from "./modal/tableForm.vue";
import conditions from "./modal/conditions.vue";
import { PersonnelPopup, DepartPopup } from "@/components";

export default {
  name: "NodeBasicConfig",
  components: {
    userPopup,
    buttonPopup,
    multiInstance,
    rolePopup,
    TDepartment,
    tableForm,
    conditions,
    PersonnelPopup,
    DepartPopup,
  },
  props: {
    modeler: {
      type: Object,
      required: true,
    },
    nodeElement: {
      type: Object,
      required: true,
    },
    formData: {
      type: Object,
      required: true,
    },
    formFieldLists: {
      type: Array,
    },
    updateList: {
      type: Array,
    },
    memberFieldLists: {
      type: Array,
    },
  },
  data() {
    return {
      isUserPopup: false,
      isUserPopups: false,
      visible: false,
      type: 0,
      radioStyle: {
        display: "block",
        height: "30px",
        lineHeight: "30px",
      },
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 4,
        },
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 20,
        },
      },
      approvalEndPointValue: 1,
      approvalEndPointSecondLevelValue: false,
      memberFieldList: [],
    };
  },
  watch: {
    nodeElement: {
      deep: true,
      immediate: true,
      handler(newVal, oldVal) {
        if (newVal.type == "bpmn:UserTask") {
          this.memberFieldList = [];
          const businessObject = newVal.businessObject;
          if (businessObject?.formFieldList) {
            const formList = JSON.parse(businessObject.formFieldList);
            formList.forEach((item) => {
              if (item.filed) {
                this.memberFieldList.push({
                  label: item.filedName,
                  filed: item.filed,
                });
              }
            });
          }
        }
      },
    },
    //
    formData: {
      deep: true,
      immediate: true,
      handler(newVal, oldVal) {
        // 编辑已有流程节点时如果选择了会签之后更换人员时，自动添加会签的状态
        if (newVal.isSequential == "false" || newVal.isSequential == "true") {
          if (newVal.candidateGroupsName || newVal.candidateUsersName) {
            this.getAssignee();
          }
        }
        // 新生成的任务节点默认设置审批人为发起人
        if (
          !newVal.assignee &&
          !newVal.userType &&
          newVal.type === "bpmn:UserTask"
        ) {
          this.getStartUser();
        }
      },
    },
    memberFieldLists: {
      deep: true,
      immediate: true,
      // 修复了如果没有选择表单布局时，不更新展示字段
      handler(newVal, oldVal) {
        if (newVal.length !== 0) {
          this.memberFieldList = newVal;
        }
      },
    },
  },
  methods: {
    // 表单变量下拉框搜索数据使用
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    // 当选择会签后再次选择指定成员/岗位角色/岗位后设置会签属性
    getAssignee() {
      if (this.formData.assignee == "${assignee}") {
        return;
      } else {
        this.updateProperties({
          assignee: "${assignee}",
        });
      }
    },
    // 给新增任务节点设置发起人为默认审批人
    getStartUser() {
      if (this.formData.assignee) {
        return;
      } else {
        this.$emit("modifyFormData", {
          userType: "processInitiator",
        });
        this.updateProperties({
          assignee: "${startUserNameId}",
          processInitiator: "${startUserNameId}",
          userType: "processInitiator",
          a: "processInitiator",
        });
      }
    },
    getFomatar(e) {
      return Boolean(e);
    },
    updateProperties(properties) {
      this.modeler
        .get("modeling")
        .updateProperties(this.nodeElement, properties);
    },
    // 节点处理人类型
    changeUserType(e) {
      this.isUserPopup = false;
      this.updateProperties({
        userType: e.target.value,
        a: e.target.value,
      });
      this.$emit("modifyFormData", {
        userType: e.target.value,
      });

      this.addUser(e.target.value, e.target.value);
    },
    // 设置节点处理人
    setUser(properties) {
      this.updateProperties(properties);
      Object.assign(properties, {
        userType: Object.keys(properties)[0],
      });
      this.$emit("modifyFormData", properties);
    },
    // 设置节点处理人
    addUser(properties, type) {
      if (this.nodeElement.businessObject?.processInitiator)
        delete this.nodeElement.businessObject.processInitiator;
      if (this.nodeElement.businessObject?.assignee)
        delete this.nodeElement.businessObject.assignee;
      if (this.nodeElement.businessObject?.assigneeName)
        delete this.nodeElement.businessObject.assigneeName;
      if (this.nodeElement.businessObject?.candidateUsers)
        delete this.nodeElement.businessObject.candidateUsers;
      if (this.nodeElement.businessObject?.candidateUsersName)
        delete this.nodeElement.businessObject.candidateUsersName;
      if (this.nodeElement.businessObject?.candidateGroups)
        delete this.nodeElement.businessObject.candidateGroups;
      if (this.nodeElement.businessObject?.candidateGroupsName)
        delete this.nodeElement.businessObject.candidateGroupsName;
      if (this.nodeElement.businessObject?.reportsTo)
        delete this.nodeElement.businessObject.reportsTo;
      if (this.nodeElement.businessObject?.reportsToName)
        delete this.nodeElement.businessObject.reportsToName;
      // 保存选择表单变量为审批人时的数据
      const formVariable = properties.value
        ? properties.value
        : properties.filedList?.key;
      var ret = {
        processInitiator: {
          userType: "processInitiator",
          processInitiator: "${startUserNameId}",
          assignee: "${startUserNameId}",
        },
        assignee: {
          userType: "assignee",
          assignee: properties.userNameId,
          assigneeName: properties.userName,
        },
        candidateUsers: {
          userType: "candidateUsers",
          candidateUsers: properties.userNameId,
          candidateUsersName: properties.userName,
        },
        candidateGroups: {
          userType: "candidateGroups",
          candidateGroups: properties.uuid,
          candidateGroupsName: properties.roleName,
        },
        department: {
          userType: "department",
          candidateGroups: properties.value,
          candidateGroupsName: properties.text,
        },
        departmentHead: {
          userType: "departmentHead",
          assignee: "${departmentHeadId}",
          assigneeName: "${departmentHeadId}",
        },
        reportsTo: {
          userType: "reportsTo",
          assignee: "${reportsToId}",
          assigneeName: "${reportsToId}",
        },
        memberFields: {
          userType: "memberFields",
          candidateUsers: "${" + formVariable + "}",
          candidateUsersName: properties.filed,
        },
      };
      properties = ret[type] ? ret[type] : "";
      this.updateProperties(properties);
      this.$emit("modifyFormData", properties);
    },
    approvalEndPointChange(e) {},
  },
};
</script>

<style lang="less">
.approved-by .title {
  color: rgba(0, 0, 0, 0.85);
  font-weight: bold;
}

.label-width label {
  width: 130px;
}

.custom-tip {
  max-width: 600px !important;

  p {
    color: #000;
  }

  .ant-tooltip-arrow::before {
    background-color: #fff !important;
  }

  .ant-tooltip-inner {
    background-color: #fff !important;
  }
}
</style>
